<template>
  <div class="content-origin">
    <el-form-item label="内容来源">
      <el-radio-group v-model="editorForm.contentOrigin.type">
        <el-radio label="category">指定栏目</el-radio>
        <el-radio label="content">指定文章</el-radio>
        <el-radio label="class">指定类型</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="editorForm.contentOrigin?.type == 'category'" label="栏目选择">
      <el-tree-select v-model="editorForm.contentOrigin.category" placeholder="未知栏目" :data="allCategory"
        :props="selectProps" default-expand-all check-strictly style="width: 180px" @change="backUpdate" />
    </el-form-item>
    <el-form-item v-if="editorForm.contentOrigin?.type == 'content'" label="文章选择">
      <div class="content-select">
        <el-button type="primary" link @click="openChooseDialog" class="add-btn">
          <el-icon><Plus /></el-icon>添加文章
        </el-button>
      </div>
    </el-form-item>
    <div v-if="editorForm.contentOrigin?.type == 'content' && selectedList.length" class="selected-articles">
      <el-scrollbar max-height="200px">
        <ul class="article-list">
          <li v-for="(item, index) in selectedList" :key="item.data_id" class="article-item">
            <el-tooltip :content="item.title" placement="top" :show-after="1000">
              <span class="title">{{ item.title }}</span>
            </el-tooltip>
            <el-button type="danger" link @click="handleDeleteContent(item, index)" class="delete-btn">
              <el-icon><Delete /></el-icon>
            </el-button>
          </li>
        </ul>
      </el-scrollbar>
    </div>
    <el-form-item v-if="editorForm.contentOrigin?.type == 'class'" label="类型选择">
      <el-tree-select v-model="editorForm.contentOrigin.class" :data="categoryContentClasses" :props="classProps"
        placeholder="请选择内容类型" default-expand-all check-strictly @change="backUpdate" />
    </el-form-item>
    <el-dialog v-model="chooseContent" title="选择文章" width="800px">
      <div class="add-user-box">
        <div class="person_body">
          <div class="person_tree">
            <!-- <el-select v-model="queryData.catId" @change="handleChangeCategory" placeholder="请选择栏目">
              <el-option v-for="item in modelCategory" :key="item.id" :label="item.name" :value="item.id" />
            </el-select> -->
            <el-tree-select v-model="queryData.catId" placeholder="请选择栏目" :data="allCategory"
              :props="queryProps" default-expand-all check-strictly @change="handleChangeCategory" />
            <ul class="select-box" v-if="contentList.length" v-infinite-scroll="scrollLoad"
              :infinite-scroll-immediate="false">
              <li v-for="item in contentList" :key="item.id" class="check_box">
                <el-checkbox v-model="item.checked" @change="handleCheckChange(item)" size="large">
                  <template #default>
                    <div class="check-box-label">
                      <span class="title">{{ item.title }}</span>
                    </div>
                  </template>
                </el-checkbox>
              </li>
            </ul>
            <el-empty v-else description="该栏目下暂未发布内容" />
          </div>
          <div class="select-result">
            <p class="clear">
              <span>已选择{{ tempSelectedList.length }}篇</span>
              <el-button type="danger" link @click="handleClearContent" :disabled="!tempSelectedList.length">清空</el-button>
            </p>
            <ul>
              <li v-for="(item, index) in tempSelectedList" :key="item.data_id">
                <span>{{ item.title }}</span>
                <i class="iconfont" @click="handleDeleteContent(item, index)">&#xeb6a;</i>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelChoose">取消</el-button>
          <el-button type="primary" @click="confirmChoose">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { inject, onMounted, ref, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import { getContentPage, getContentDetails } from '@/api/content'
import { Delete, Plus } from '@element-plus/icons-vue'

const store = useStore()
const { editorForm, backUpdate } = inject('commonForm')
const contentList = ref([])
const selectedList = ref([])
const selectedIds = ref([])
const tableLoading = ref(false)
const total = ref(0)
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 20,
  catId: null // 默认为6，即新闻
})
const queryData = ref(Object.assign({}, defaultQueryData))
const _getContentPage = async () => {
  tableLoading.value = true
  let res = await getContentPage(queryData.value)
  // 检测是否有已选择的，有就为其添加checked属性
  res.data.list.forEach(item => {
    if (selectedIds.value.includes(item.data_id)) {
      item.checked = true
    }
  })
  contentList.value.push(...res.data.list)
  total.value = res.data.total
  tableLoading.value = false
}
// 切换栏目，重新获取内容列表
const queryProps = reactive({
  children: 'children',
  label: 'name',
  value: 'id',
  disabled: (data) => {
    return !data.modelId || data.modelId == -1
  }
})
const handleChangeCategory = () => {
  queryData.value.currentPage = 1
  contentList.value = []
  _getContentPage()
}
// 触底加载内容列表
const scrollLoad = () => {
  if (contentList.value.length === total.value) return
  queryData.value.currentPage++
  _getContentPage()
}
// 左侧切换文章勾选
const handleCheckChange = data => {
  if (data.checked) {
    tempSelectedList.value.push(data)
  } else {
    const selectedIndex = tempSelectedList.value.findIndex(item => item.id === data.id)
    if (selectedIndex !== -1) {
      tempSelectedList.value.splice(selectedIndex, 1)
    }
  }
}
// 右侧删除文章
const handleDeleteContent = (data, index) => {
  if (chooseContent.value) {
    tempSelectedList.value.splice(index, 1)
  } else {
    selectedList.value.splice(index, 1)
    backUpdate()
  }
  const contentIndex = contentList.value.findIndex(item => item.id === data.id)
  if (contentIndex !== -1) {
    contentList.value[contentIndex].checked = false
  }
}
// 右侧清除全部已选
const handleClearContent = () => {
  if (chooseContent.value) {
    tempSelectedList.value.forEach(item => {
      const contentIndex = contentList.value.findIndex(contentItem => contentItem.id === item.id)
      if (contentIndex !== -1) {
        contentList.value[contentIndex].checked = false
      }
    })
    tempSelectedList.value = []
  } else {
    selectedList.value = []
  }
}
watch(
  selectedList,
  newVal => {
    let formatObj = {}
    let ids = []
    newVal.forEach(item => {
      const catId = item.cat_id
      if (!formatObj[catId]) {
        formatObj[catId] = {
          catId,
          dataIds: []
        }
      }
      formatObj[catId].dataIds.push(item.data_id)
      ids.push(item.data_id)
    })
    editorForm.value.contentOrigin.content = Object.values(formatObj).map(item => ({ ...item, catId: item.catId }))
    selectedIds.value = ids
  },
  { deep: true }
)
// 回显已选文章的详情
const echoContentDetail = async () => {
  const res = await getContentDetails({ list: editorForm.value.contentOrigin.content })
  if (res.code === 20000) {
    selectedList.value = res.data
  }
}
// 获取所有栏目
const allCategory = ref([])
const modelCategory = ref([])
const selectProps = reactive({
  children: 'children',
  label: 'name',
  value: 'id',
  disabled: (data) => {
    return data.state === 1
  }
})
const _getAllCategory = async () => {
  allCategory.value = store.state.category.categoryTree
  modelCategory.value = store.state.category.categoryFlat.filter(item => item.modelId && item.modelId != -1 && item.siteId === store.state.site.currentSite.id)
  queryData.value.catId = modelCategory.value[0].id
}
// 类型选择
const categoryContentClasses = ref([])
const classProps = reactive({
  children: 'children',
  label: 'label',
  value: 'value',
  disabled: (data) => {
    return data.children && true
  }
})
const _getCategoryContentClass = async () => {
  let modelList = store.state.content.modelList
  if (!modelList || modelList.length === 0) {
    modelList = await store.dispatch('content/updateModelList')
  }
  // 格式化数据,添加 disabled 属性
  categoryContentClasses.value = modelList.map(item => {
    return {
      label: item.name,
      value: item.id,
      children: item.contentClasses || []
    }
  })
}

// 新增的响应式变量
const chooseContent = ref(false)
const tempSelectedList = ref([]) // 用于弹窗中临时存储选中的文章

// 新增的方法
const openChooseDialog = () => {
  tempSelectedList.value = [...selectedList.value]
  chooseContent.value = true
  if (contentList.value.length === 0) {
    _getContentPage()
  }
}

const cancelChoose = () => {
  chooseContent.value = false
  // 重置临时选择状态
  contentList.value.forEach(item => {
    item.checked = selectedList.value.some(selected => selected.id === item.id)
  })
}

const confirmChoose = () => {
  selectedList.value = [...tempSelectedList.value]
  chooseContent.value = false
  backUpdate()
}

onMounted(async () => {
  await _getAllCategory()
  if (editorForm.value.contentOrigin?.content?.length > 0) {
    queryData.value.catId = editorForm.value.contentOrigin.content[0].catId
    await echoContentDetail()
  }
  await _getCategoryContentClass()
  await _getContentPage()
})
</script>

<style lang="scss" scoped>
.content-origin {
  .add-user-box {
    width: 100%;
    .person_body {
      border: 1px solid #f5f5f5;
      height: 400px;
      display: flex;
      .person_tree {
        padding: 10px 12px 0 15px;
        width: 50%;
        height: 100%;
        border-right: 1px solid #f5f5f5;
        box-sizing: border-box;
        .select-box {
          height: 356px;
          overflow-y: auto;
          padding: 0;
          li {
            .el-checkbox__input {
              display: inline-block;
            }
            .check-box-label {
              display: flex;
              align-items: center;
              .title {
                @include textEllipsis(18px, 1);
              }
            }
            i {
              float: right;
              padding-right: 10px;
              color: #3195f8;
              font-size: 14px;
              cursor: pointer;
            }

            a.active + i {
              color: rgb(197, 197, 197);
              // background-image: url(~@/assets/audit/next_level.png);
              pointer-events: none;
            }

            img {
              width: 14px;
              vertical-align: middle;
              margin-right: 5px;
            }
          }
        }
      }
      .select-result {
        width: 50%;
        height: 400px;
        font-size: 14px;
        overflow: hidden;
        p {
          padding: 9px 12px 0 15px;
          border-bottom: 1px solid #f2f2f2;
          display: flex;
          justify-content: space-between;
          align-items: center;
          line-height: 32px;
        }
        ul {
          height: 356px;
          overflow-y: auto;
          padding: 0 12px 0 15px;
          li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 40px;
            line-height: 40px;
            span {
              vertical-align: middle;
              @include textEllipsis(18px, 1);
            }
            i {
              font-size: 12px;
              color: #606266;
              cursor: pointer;
            }
            i:hover {
              color: $mainColor;
            }
          }
        }
      }
    }
  }

  .content-select {
    .add-btn {
      padding: 0;
      height: 32px;
      margin-bottom: 8px;
      
      .el-icon {
        margin-right: 4px;
      }
    }
    
  }
  .selected-articles {
    margin-top: -15px;
    margin-bottom: 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    max-height: 200px;
    
    .article-list {
      margin: 0;
      padding: 0;
      list-style: none;
      
      .article-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px;
        border-bottom: 1px solid #f0f0f0;
        font-size: 12px;
        
        &:last-child {
          border-bottom: none;
        }
        
        .title {
          flex: 1;
          margin-right: 8px;
          @include textEllipsis(16px, 1);
          color: #606266;
        }
        
        .delete-btn {
          padding: 0;
          height: 24px;
          color: #f56c6c;
          
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
  }
}
</style>
